import React, { useState, useEffect } from 'react';
import { Users, Clock, AlertTriangle, CheckCircle, RefreshCw, Activity, AlertCircle } from 'lucide-react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { monitorApi } from '../../services/monitor';
import type { ConsumerGroupMetrics, ConsumerGroupLagHistory } from '../../types/monitor';

interface ConsumerGroupMonitorProps {
  refreshInterval?: number;
}

const ConsumerGroupMonitor: React.FC<ConsumerGroupMonitorProps> = ({
  refreshInterval = 30000
}) => {
  const [loading, setLoading] = useState(false);
  const [metrics, setMetrics] = useState<ConsumerGroupMetrics | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 获取消费者组指标
  const fetchConsumerGroupMetrics = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await monitorApi.getConsumerGroupsMetrics();
      if (response.success) {
        setMetrics(response.data);
      }
    } catch (error) {
      console.error('获取消费者组指标失败:', error);
      setError('获取消费者组指标失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchConsumerGroupMetrics();
    const interval = setInterval(fetchConsumerGroupMetrics, refreshInterval);
    return () => clearInterval(interval);
  }, [refreshInterval]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        <span className="ml-2">加载中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center">
          <AlertTriangle className="w-5 h-5 text-red-500 mr-2" />
          <span className="text-red-700">{error}</span>
        </div>
      </div>
    );
  }

  if (!metrics) {
    return (
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
        <div className="text-center text-gray-500">暂无数据</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 概览统计 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <Users className="w-8 h-8 text-blue-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">总消费者组</p>
              <p className="text-2xl font-bold text-gray-900">{metrics.total_groups}</p>
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <CheckCircle className="w-8 h-8 text-green-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">活跃消费者组</p>
              <p className="text-2xl font-bold text-gray-900">{metrics.active_groups}</p>
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <AlertTriangle className="w-8 h-8 text-yellow-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">总Lag</p>
              <p className="text-2xl font-bold text-gray-900">{metrics.total_lag.toLocaleString()}</p>
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <RefreshCw 
              className={`w-8 h-8 text-blue-500 mr-3 cursor-pointer ${loading ? 'animate-spin' : ''}`}
              onClick={fetchConsumerGroupMetrics}
            />
            <div>
              <p className="text-sm font-medium text-gray-600">刷新</p>
              <p className="text-sm text-gray-500">点击刷新数据</p>
            </div>
          </div>
        </div>
      </div>

      {/* 消费者组列表 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900">消费者组列表</h3>
        </div>
        <div className="p-6">
          {Object.keys(metrics.consumer_groups).length === 0 ? (
            <div className="text-center text-gray-500 py-8">暂无消费者组</div>
          ) : (
            // 消费者组列表 - 添加独立滚动，活跃的排在前面
            <div className="max-h-96 overflow-y-auto space-y-4">
              {Object.entries(metrics.consumer_groups)
                // 排序：活跃的消费者组排在前面
                .sort(([, a], [, b]) => {
                  if (a.is_active && !b.is_active) return -1;
                  if (!a.is_active && b.is_active) return 1;
                  return a.group_id.localeCompare(b.group_id);
                })
                .map(([groupId, groupData]) => {
                  // 判断消费者组是否已过期（没有活跃成员且状态为Unknown）
                  const isExpired = !groupData.is_active && groupData.state === 'Unknown';

                  return (
                    <div
                      key={groupId}
                      className={`border rounded-lg p-4 ${
                        groupData.is_active
                          ? 'border-green-200 bg-green-50'
                          : isExpired
                            ? 'border-gray-300 bg-gray-50'
                            : 'border-gray-200'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center">
                          <Users className={`w-5 h-5 mr-2 ${
                            groupData.is_active
                              ? 'text-green-500'
                              : isExpired
                                ? 'text-gray-400'
                                : 'text-blue-500'
                          }`} />
                          <span className={`font-medium ${
                            groupData.is_active
                              ? 'text-green-900'
                              : isExpired
                                ? 'text-gray-500'
                                : 'text-gray-900'
                          }`}>
                            {groupId}
                          </span>
                          <span className={`ml-2 px-2 py-1 text-xs rounded-full ${
                            isExpired
                              ? 'bg-red-100 text-red-800'
                              : groupData.is_active
                                ? 'bg-green-100 text-green-800'
                                : groupData.state === 'Stable'
                                  ? 'bg-green-100 text-green-800'
                                  : 'bg-yellow-100 text-yellow-800'
                          }`}>
                            {isExpired ? '已过期' : groupData.state}
                          </span>
                        </div>
                        <div className="flex items-center space-x-4 text-sm text-gray-500">
                          <span>成员: {groupData.members}</span>
                          <span>Lag: {groupData.total_lag.toLocaleString()}</span>
                          <span>Topics: {Object.keys(groupData.topics).length}</span>
                        </div>
                      </div>
                    </div>
                  );
                })}
            </div>
          )}
        </div>
      </div>

      {/* 背压指标面板 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900">背压指标</h3>
          <p className="text-sm text-gray-500">系统背压和性能瓶颈监控</p>
        </div>
        <div className="p-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* 高延迟组 */}
            <div className="bg-red-50 rounded-lg p-4 border border-red-200">
              <div className="flex items-center mb-3">
                <AlertTriangle className="w-5 h-5 text-red-500 mr-2" />
                <h4 className="font-medium text-red-900">高延迟组</h4>
              </div>
              <div className="text-2xl font-bold text-red-900 mb-1">
                {metrics.backpressure_indicators?.high_lag_groups?.length || 0}
              </div>
              <p className="text-sm text-red-600">个消费者组</p>
              {metrics.backpressure_indicators?.high_lag_groups?.length > 0 && (
                <div className="mt-3 space-y-1">
                  {metrics.backpressure_indicators.high_lag_groups.slice(0, 3).map((groupId) => (
                    <div key={groupId} className="text-xs text-red-700 bg-red-100 px-2 py-1 rounded">
                      {groupId}
                    </div>
                  ))}
                  {metrics.backpressure_indicators.high_lag_groups.length > 3 && (
                    <div className="text-xs text-red-600">
                      +{metrics.backpressure_indicators.high_lag_groups.length - 3} 更多...
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 慢消费者 */}
            <div className="bg-yellow-50 rounded-lg p-4 border border-yellow-200">
              <div className="flex items-center mb-3">
                <Clock className="w-5 h-5 text-yellow-500 mr-2" />
                <h4 className="font-medium text-yellow-900">慢消费者</h4>
              </div>
              <div className="text-2xl font-bold text-yellow-900 mb-1">
                {metrics.backpressure_indicators?.slow_consumers?.length || 0}
              </div>
              <p className="text-sm text-yellow-600">个消费者组</p>
              {metrics.backpressure_indicators?.slow_consumers?.length > 0 && (
                <div className="mt-3 space-y-1">
                  {metrics.backpressure_indicators.slow_consumers.slice(0, 3).map((groupId) => (
                    <div key={groupId} className="text-xs text-yellow-700 bg-yellow-100 px-2 py-1 rounded">
                      {groupId}
                    </div>
                  ))}
                  {metrics.backpressure_indicators.slow_consumers.length > 3 && (
                    <div className="text-xs text-yellow-600">
                      +{metrics.backpressure_indicators.slow_consumers.length - 3} 更多...
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 不健康组 */}
            <div className="bg-orange-50 rounded-lg p-4 border border-orange-200">
              <div className="flex items-center mb-3">
                <AlertCircle className="w-5 h-5 text-orange-500 mr-2" />
                <h4 className="font-medium text-orange-900">不健康组</h4>
              </div>
              <div className="text-2xl font-bold text-orange-900 mb-1">
                {metrics.backpressure_indicators?.unhealthy_groups?.length || 0}
              </div>
              <p className="text-sm text-orange-600">个消费者组</p>
              {metrics.backpressure_indicators?.unhealthy_groups?.length > 0 && (
                <div className="mt-3 space-y-1">
                  {metrics.backpressure_indicators.unhealthy_groups.slice(0, 3).map((groupId) => (
                    <div key={groupId} className="text-xs text-orange-700 bg-orange-100 px-2 py-1 rounded">
                      {groupId}
                    </div>
                  ))}
                  {metrics.backpressure_indicators.unhealthy_groups.length > 3 && (
                    <div className="text-xs text-orange-600">
                      +{metrics.backpressure_indicators.unhealthy_groups.length - 3} 更多...
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* 背压状态总结 */}
          <div className="mt-6 p-4 bg-gray-50 rounded-lg">
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <Activity className="w-5 h-5 text-gray-500 mr-2" />
                <span className="font-medium text-gray-900">系统背压状态</span>
              </div>
              <div className={`px-3 py-1 rounded-full text-sm font-medium ${
                (metrics.backpressure_indicators?.high_lag_groups?.length || 0) > 0 ||
                (metrics.backpressure_indicators?.slow_consumers?.length || 0) > 0 ||
                (metrics.backpressure_indicators?.unhealthy_groups?.length || 0) > 0
                  ? 'bg-red-100 text-red-800'
                  : 'bg-green-100 text-green-800'
              }`}>
                {(metrics.backpressure_indicators?.high_lag_groups?.length || 0) > 0 ||
                 (metrics.backpressure_indicators?.slow_consumers?.length || 0) > 0 ||
                 (metrics.backpressure_indicators?.unhealthy_groups?.length || 0) > 0
                  ? '存在背压'
                  : '正常'}
              </div>
            </div>
            <p className="text-sm text-gray-600 mt-2">
              {(metrics.backpressure_indicators?.high_lag_groups?.length || 0) > 0 ||
               (metrics.backpressure_indicators?.slow_consumers?.length || 0) > 0 ||
               (metrics.backpressure_indicators?.unhealthy_groups?.length || 0) > 0
                ? '检测到系统背压，建议检查消费者组性能和资源配置'
                : '所有消费者组运行正常，无背压问题'}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConsumerGroupMonitor;
